import confg from './config';
const baseurl = confg.base_url + '/api/v1';

function getImageInfo(url) {
  return new Promise((resolve, reject) => {
    wx.getImageInfo({
      src: url,
      success: resolve,
      fail: reject,
    })
  })
}

function bgImg(othis, canvasId, ww, hh, imgs) {
  //注意这里的 canvas 要与wxml文件的canvas-id属性命名一样
  const ctx = wx.createCanvasContext(canvasId);
  const data = othis.data.detail;
  let side = 30;
  let canvaslogo = "../../images/code-share-logo.png"; //图片路径不要出错

  // 画背景
  ctx.beginPath()
  ctx.setFillStyle('#f6f6f6')
  ctx.rect(0, 0, ww, hh)
  ctx.fill()
  roundRect(ctx, side, side * 2, ww - side * 2, hh - side * 3, 10)
  ctx.setFillStyle('white')
  ctx.fill()

  arrSplit(data.pay_type, confg.drop_type, ctx, ww - side * 2, side * 2 + 20 + 14)
  ctx.beginPath()
  ctx.setFillStyle('#fef4f3')
  ctx.rect(side + 10, side * 2 + 90, 160, 20)
  ctx.fill()
  ctx.beginPath()
  ctx.setFillStyle('#fff')
  ctx.rect(side + 80, side * 2 + 92, 80, 16)
  ctx.fill()
  ctx.setFontSize(12)
  ctx.setFillStyle('#cd586b')
  ctx.fillText('截止日期', side + 20, side * 2 + 90 + 14)
  ctx.fillText(data.end_time, side + 80 + 10, side * 2 + 90 + 14)

  ctx.setFillStyle('#000')
  ctx.setFontSize(18)

  titleFn(data, ctx, side + 10, side * 2 + 50 + 18, ww)
  ctx.fillText('详细要求', side + 10, side * 2 + 228)
  ctx.setFontSize(14)
  // ctx.fillText('报名上限：' + data.numbers, side + 10, side * 2 + 130)
  numbersFn(data,ctx,side + 10, side * 2 + 130)
  pingpaiFn(data, ctx, side + 10, side * 2 + 160)
  // ctx.fillText('产品品牌：' + data.product_name, side + 10, side * 2 + 160)
  ctx.fillText('达人领域：' + data.domain[0].name, side + 10, side * 2 + 190)
  huanhang(data.detailed, ctx, side + 10, side * 2 + 260, ww, 1)
  ctx.beginPath()
  ctx.setFillStyle('red')
  ctx.rect(side, side * 2 + 50, 5, 20)
  ctx.fill()

  ctx.setFillStyle('red')
  ctx.rect(side, side * 2 + 210, 5, 20)
  ctx.fill()
  ctx.drawImage(imgs, ww - side * 2 - 80, hh - side * 2 - 80, 100, 100)
  ctx.drawImage(canvaslogo, side, side * 0.7, 90, 30)
  ctx.draw(); //绘制背景图片
  setTimeout(() => {
    wx.hideLoading()
    wx.canvasToTempFilePath({
      canvasId: canvasId,
      x: 0,
      y: 0,
      width: ww,
      height: hh,
      quality: 1,
      success(res) {
        wx.previewImage({
          current: res.tempFilePath,
          urls: [res.tempFilePath]
        });
      },
      fail: function (err) {
        console.log(err)
      }
    }, othis);
  }, 500)
}

function roundRect(ctx, x, y, w, h, r) {
  // 开始绘制
  ctx.beginPath()
  // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
  // 这里是使用 fill 还是 stroke都可以，二选一即可
  ctx.setFillStyle('transparent')
  // ctx.setStrokeStyle('transparent')
  // 左上角
  ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
  // border-top
  ctx.moveTo(x + r, y)
  ctx.lineTo(x + w - r, y)
  ctx.lineTo(x + w, y + r)
  // 右上角
  ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
  // border-right
  ctx.lineTo(x + w, y + h - r)
  ctx.lineTo(x + w - r, y + h)
  // 右下角
  ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
  // border-bottom
  ctx.lineTo(x + r, y + h)
  ctx.lineTo(x, y + h - r)
  // 左下角
  ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
  // border-left
  ctx.lineTo(x, y + r)
  ctx.lineTo(x + r, y)
  // 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
  ctx.fill()
  // ctx.stroke()
  ctx.closePath()
  // 剪切
  // ctx.clip()
}

function titleFn(data, ctx, x, y, ww) {
  let maxw = ww - x * 2
  let ind = parseInt(maxw / 18)
  let text = '';
  if(data.title){
    confg.task_type.forEach(el=>{
      if(el.imgurl_s==data.platform){
        text = `【${el.name}】`
      }
    })
    text += data.title;
  }else{
    text = `【${data.commerce.name}】${data.product_name}`
  }
  if (text.length > ind) {
    text = text.slice(0, ind) + '...'
  }
  ctx.fillText(text, x, y)
}
function pingpaiFn(data, ctx, x, y, ww) {
  let maxw = ww - x * 2
  let ind = parseInt(maxw / 18)
  let text = data.title ? data.title : data.product_name;
  if(data.title){
    text = "产品品牌：" +data.product_name
  }else{
    text = "推广价格：" +data.price
  }
  if (text.length > ind) {
    text = text.slice(0, ind) + '...'
  }
  ctx.fillText(text, x, y)
}
// 报名上限
function numbersFn(data, ctx, x, y, ww) {
  let text = '';
  if(data.title){
    text = "报名上限：" +data.numbers
  }else{
    text = "佣金比例：" +data.commission + "%"
  }
  ctx.fillText(text, x, y)
}
// 佣金版块
function arrSplit(e, arr, ctx, ww, y) {
  let ind = 1;
  e = [e[0]];
  e.forEach(eel => {
    arr.forEach(el => {
      if (el.id == eel) {
        drows(el.name, ww, y)
        ind++
      }
    })
  })

  function drows(text, ww, y) {
    let txw = text.length * 17
    ctx.beginPath()
    ctx.setFillStyle('#fef4f3')
    ctx.rect(ww - txw, y - 14, txw, 20)
    ctx.fill()
    ctx.setFillStyle('#cd586b')
    ctx.setFontSize(14)
    ctx.fillText(text, ww - txw + 5, y)
  }
}
// 详情
function huanhang(text, ctx, x, y, ww, ind) {
  ind++;
  let maxw = ww - x * 2;
  let startindex = parseInt(maxw / 14),
    startindex1 = startindex;
  let arr = text.split('');
  for (let i = 0; i < arr.length; i++) {
    if (escape(arr[i]).replace(/\%u/g, '/u') == '%0A') {
      startindex1 = i;
      break
    }
  }
  if (startindex1 < startindex) {
    startindex = startindex1
  }
  ctx.fillText(text.slice(0, startindex), x, y)
  if (ind == 6) {
    huanhang('...', ctx, x, y + 20, ww, ind)
  }
  if (startindex < text.length && ind <= 5) {
    huanhang(text.slice(startindex + 1), ctx, x, y + 20, ww, ind)
  }
}

function codeShareFn(canvasId, type, othis) {
  wx.showLoading({
    title: '加载中',
    mask: true
  })
  wx.getSystemInfo({
    success(sys) { // 获取设备信息，开始压缩，并处理回调
      let ww = sys.screenWidth,
        hh = ww * 1.5
      othis.setData({
        sw: ww,
        sh: hh
      })
      let ob = {
        cid: othis.data.detail.id,
        s: type
      }
      wx.request({
        url: baseurl + '/member/image',
        data: ob,
        method: 'POST',
        header: {
          'content-type': 'application/json',
          'authorization': wx.getStorageSync('token_')
        },
        success: function (res) { //服务器返回数据
          getImageInfo(confg.base_url+res.data.data).then(cc=>{
            bgImg(othis, canvasId, ww, hh, cc.path)
          }).catch(err => {
            bgImg(othis, canvasId, ww, hh, '../../images/code-share-qr.png')
          })
        },
        error: function (e) {
         
        }
      })


    }
  })
}
export default {
  fns: codeShareFn
}